package com.cyk.controller;

import com.cyk.dao.LagouAuthCodeDao;
import com.cyk.feigh.EmailFeighClient;
import com.cyk.pojo.LagouAuthCode;
import com.cyk.util.ToolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/code")
public class CodeController {
    @Autowired
    private LagouAuthCodeDao lagouAuthCodeDao;

    @Autowired
    private EmailFeighClient emailFeighClient;


    /*
    ⽣生成验证码并发送到对应邮箱，成功true，失败 false
     */
    @GetMapping("/create/{email}")
    public Boolean create(@PathVariable String email) {
        String code = Integer.toString(ToolUtil.getInstance().getCode());
        return emailFeighClient.email(email, code);
    }

    /*
    0/1/2 校验验证码是否正确，0正确1错误2超时
     */
    @GetMapping("/validate/{email}/{code}")
    public Integer validate(@PathVariable String email, @PathVariable String code) {
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        List<LagouAuthCode> list = lagouAuthCodeDao.findAll(Example.of(lagouAuthCode));
        if (list.isEmpty()) {
            return 1;
        }
        List<LagouAuthCode> sortList = list.stream().sorted(Comparator.comparing(LagouAuthCode::getId)).collect(Collectors.toList());
        LagouAuthCode lagouAuthCode1 = sortList.get(sortList.size() - 1);
        if (!lagouAuthCode1.getCode().equals(code)) {
            return 1;
        }
        if (list.get(0).getExpiretime().getTime() < new Date().getTime()) {
            return 2;
        }
        return 0;
    }
}